const api = require("../method/api");
const fs = require("fs");
const path = require("path");
const base_path = "";

/**
 *
 * header 加载头部
 * @param {*} err
 */
exports.header = function(arr){
  return new Promise((resolve, reject) => {
    let str = arr[0];
    let params = getParams(str);
    if(params.name){
      let p = path.resolve(__dirname,"../template/",params.name);
      fs.readFile(p,'utf8',function(err,result){
        let h = result;
        h = h.replace(/\{\$path\}/g,base_path);
        resolve(h)
      })
    }else{
      resolve("未找到模板")
    }
  });
}

/**
 *
 * footer 加载尾部
 * @param {*} err
 */
exports.footer = function(arr){
  return new Promise((resolve, reject) => {
    let str = arr[0];
    let params = getParams(str);
    if(params.name){
      let p = path.resolve(__dirname,"../template/",params.name);
      fs.readFile(p,'utf8',function(err,result){
        let h = result;
        h = h.replace(/\{\$path\}/g,base_path);
        resolve(h)
      })
    }else{
      resolve("未找到模板")
    }
  });
}

/**
 *
 * content 用于调取指定id的内容
 * @param {*} arr
 */
exports.content = function(arr){
  let str = arr[0];
  let params = getParams(str);
  let obj = getBody(str);
  let h = "";
  api.content(function(err,data){
    if(err){
      console.log('请求参数失败')
    }
    for(let i of data){
      let b = obj.body; 
      for(let j in i){
        let j_reg = RegExp("\\{\\$"+j+"\\}"); 
        b = b.replace(j_reg,i[j])
      }
      h += b;
    }
  },obj.field,params)
  return h;
}

// if语句
exports.if = function(arr){
  
}

// 获取参数
function getParams(str){
  let params_reg = RegExp(/(?<=\{yx:[a-z]+\s)[\s\S]*?(?=\})/g); 
  let params_arr = [];
  let res = {};
  while((params_arr = params_reg.exec(str)) != null){
    let params_str = params_arr[0];
    let params_child_reg = RegExp(/([\S]+=[\S]+)+/g);
    while((params_arr = params_child_reg.exec(params_str)) != null){
      let s = params_arr[0]; 
      let params_name_reg = RegExp(/[\S]+(?==)/);
      let params_value_reg = RegExp(/(?<==)[\S]+/);
      let params_name = params_name_reg.exec(s)[0];
      let params_value = params_value_reg.exec(s)[0];
      res[params_name] = params_value;
    }
  }
  return res;
}

// 获取body,解析body内字段名
function getBody(str){
  let data = {};
  let field_arr = [];
  let body_reg = RegExp(/(?<=\{yx:[a-z]+[\s\S]+?\})([\s\S]*?)(?=\{\/yx:[a-z]+\})/g);
  let body = "";
  while((field_arr = body_reg.exec(str)) != null){
    body = field_arr[0];
  }
  let field_reg = RegExp(/(?<=\{\$)\w+(?=[^a-zA-Z]+)/g);
  let field = "";
  while((field_arr = field_reg.exec(str)) != null){
    field = field + field_arr[0] + ",";
  }
  field = field.substring(0,field.length-1)
  data.body = body;
  data.field = field;
  return data;
}